from datetime import datetime
from typing import List, Optional, Dict, Any
from fastapi import APIRouter, Depends, Query, Path, Body, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from module_speech.service.speech_client_service import ClientUserService
from module_speech.service.speech_usage_service import ClientUsageService
from module_speech.service.speech_quota_service import QuotaService
from module_speech.entity.vo.speech_client_vo import (
    ClientUserModel, ClientUserCreateModel, ClientUserUpdateModel,
    ClientUserQueryModel, ApiKeyModel, QuotaModel
)
from utils.response_util import ResponseUtil
from utils.page_util import PageResponseModel
from config.get_db import get_db
from module_admin.service.login_service import LoginService
from utils.log_util import logger


router = APIRouter(prefix="/speech/clients", tags=["语音识别-客户端用户管理"])


@router.post("/")
async def create_client_user(
    user_data: ClientUserCreateModel,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    创建客户端用户
    """
    try:
        # 权限检查：只有管理员可以创建客户端用户
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以创建客户端用户")
        
        # 创建客户端用户
        result = await ClientUserService.create_client_user(db, user_data)
        
        return ResponseUtil.success(data=result.dict(), message="客户端用户创建成功")
        
    except Exception as e:
        logger.error(f"创建客户端用户失败: {str(e)}")
        return ResponseUtil.error(message=f"创建客户端用户失败: {str(e)}")


@router.get("/")
async def get_client_users(
    username: Optional[str] = Query(None, description="用户名"),
    email: Optional[str] = Query(None, description="邮箱"),
    client_type: Optional[int] = Query(None, description="客户端类型"),
    plan_type: Optional[str] = Query(None, description="计划类型"),
    status: Optional[int] = Query(None, description="状态"),
    page_num: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    获取客户端用户列表
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以查看客户端用户列表")
        
        # 构建查询参数
        query_params = ClientUserQueryModel(
            username=username,
            email=email,
            client_type=client_type,
            plan_type=plan_type,
            status=status,
            page_num=page_num,
            page_size=page_size
        )
        
        # 获取用户列表
        result = await ClientUserService.get_client_users(db, query_params)
        
        return ResponseUtil.success(data=result, message="获取客户端用户列表成功")
        
    except Exception as e:
        logger.error(f"获取客户端用户列表失败: {str(e)}")
        return ResponseUtil.error(message=f"获取客户端用户列表失败: {str(e)}")


@router.get("/{client_user_id}")
async def get_client_user_detail(
    client_user_id: int = Path(..., description="客户端用户ID"),
    include_sensitive: bool = Query(False, description="是否包含敏感信息"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    获取客户端用户详情
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以查看客户端用户详情")
        
        # 获取用户详情
        result = await ClientUserService.get_client_user_by_id(
            db, client_user_id, include_sensitive
        )
        
        return ResponseUtil.success(data=result.dict(), message="获取客户端用户详情成功")
        
    except Exception as e:
        logger.error(f"获取客户端用户详情失败: {str(e)}")
        return ResponseUtil.error(message=f"获取客户端用户详情失败: {str(e)}")


@router.put("/{client_user_id}")
async def update_client_user(
    client_user_id: int = Path(..., description="客户端用户ID"),
    user_data: ClientUserUpdateModel = Body(...),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    更新客户端用户信息
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以更新客户端用户")
        
        # 更新用户信息
        result = await ClientUserService.update_client_user(db, client_user_id, user_data)
        
        return ResponseUtil.success(data=result.dict(), message="客户端用户更新成功")
        
    except Exception as e:
        logger.error(f"更新客户端用户失败: {str(e)}")
        return ResponseUtil.error(message=f"更新客户端用户失败: {str(e)}")


@router.delete("/{client_user_id}")
async def delete_client_user(
    client_user_id: int = Path(..., description="客户端用户ID"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    删除客户端用户
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以删除客户端用户")
        
        # 删除用户
        result = await ClientUserService.delete_client_user(db, client_user_id)
        
        if result:
            return ResponseUtil.success(message="客户端用户删除成功")
        else:
            return ResponseUtil.error(message="删除客户端用户失败")
        
    except Exception as e:
        logger.error(f"删除客户端用户失败: {str(e)}")
        return ResponseUtil.error(message=f"删除客户端用户失败: {str(e)}")


@router.post("/{client_user_id}/reset-api-key")
async def reset_api_key(
    client_user_id: int = Path(..., description="客户端用户ID"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    重置API密钥
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以重置API密钥")
        
        # 重置API密钥
        result = await ClientUserService.reset_api_keys(db, client_user_id)
        
        return ResponseUtil.success(data=result.dict(), message="API密钥重置成功")
        
    except Exception as e:
        logger.error(f"重置API密钥失败: {str(e)}")
        return ResponseUtil.error(message=f"重置API密钥失败: {str(e)}")


@router.put("/{client_user_id}/quota")
async def update_quota_settings(
    client_user_id: int = Path(..., description="客户端用户ID"),
    quota_monthly: int = Body(..., description="月度配额（分钟）"),
    rate_limit_per_minute: Optional[int] = Body(None, description="每分钟请求限制"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    更新配额设置
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以更新配额设置")
        
        # 更新配额设置
        result = await ClientUserService.update_quota_settings(
            db, client_user_id, quota_monthly, rate_limit_per_minute
        )
        
        if result:
            return ResponseUtil.success(message="配额设置更新成功")
        else:
            return ResponseUtil.error(message="配额设置更新失败")
        
    except Exception as e:
        logger.error(f"更新配额设置失败: {str(e)}")
        return ResponseUtil.error(message=f"更新配额设置失败: {str(e)}")


@router.get("/{client_user_id}/quota")
async def get_quota_usage(
    client_user_id: int = Path(..., description="客户端用户ID"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    获取配额使用情况
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以查看配额使用情况")
        
        # 获取配额使用情况
        result = await ClientUserService.get_quota_usage(db, client_user_id)
        
        return ResponseUtil.success(data=result.dict(), message="获取配额使用情况成功")
        
    except Exception as e:
        logger.error(f"获取配额使用情况失败: {str(e)}")
        return ResponseUtil.error(message=f"获取配额使用情况失败: {str(e)}")


@router.get("/{client_user_id}/usage")
async def get_client_usage_records(
    client_user_id: int = Path(..., description="客户端用户ID"),
    start_date: Optional[str] = Query(None, description="开始日期 (YYYY-MM-DD)"),
    end_date: Optional[str] = Query(None, description="结束日期 (YYYY-MM-DD)"),
    page_num: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    获取客户端用户使用记录
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以查看使用记录")
        
        # 构建查询参数
        from module_speech.entity.vo.speech_client_vo import ClientUsageQueryModel
        from datetime import datetime
        
        query_params = ClientUsageQueryModel(
            client_user_id=client_user_id,
            start_date=datetime.strptime(start_date, '%Y-%m-%d').date() if start_date else None,
            end_date=datetime.strptime(end_date, '%Y-%m-%d').date() if end_date else None,
            page_num=page_num,
            page_size=page_size
        )
        
        # 获取使用记录
        result = await ClientUsageService.get_usage_records(db, query_params)
        
        return ResponseUtil.success(data=result, message="获取使用记录成功")
        
    except Exception as e:
        logger.error(f"获取使用记录失败: {str(e)}")
        return ResponseUtil.error(message=f"获取使用记录失败: {str(e)}")


@router.get("/statistics/overview")
async def get_client_user_statistics(
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    获取客户端用户统计概览
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以查看统计信息")
        
        # 获取统计信息
        result = await ClientUserService.get_client_user_statistics(db)
        
        return ResponseUtil.success(data=result, message="获取统计信息成功")
        
    except Exception as e:
        logger.error(f"获取统计信息失败: {str(e)}")
        return ResponseUtil.error(message=f"获取统计信息失败: {str(e)}")


@router.post("/{client_user_id}/quota/reset")
async def reset_user_quota(
    client_user_id: int = Path(..., description="客户端用户ID"),
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    重置用户配额
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以重置配额")
        
        # 重置配额
        result = await QuotaService.reset_monthly_quota(db, client_user_id)
        
        if result:
            return ResponseUtil.success(message="配额重置成功")
        else:
            return ResponseUtil.error(message="配额重置失败")
        
    except Exception as e:
        logger.error(f"重置配额失败: {str(e)}")
        return ResponseUtil.error(message=f"重置配额失败: {str(e)}")


@router.get("/quota/alerts")
async def get_quota_alerts(
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(LoginService.get_current_user)
):
    """
    获取配额告警列表
    """
    try:
        # 权限检查
        if current_user.get('user_type') != 'admin':
            return ResponseUtil.forbidden(message="权限不足，只有管理员可以查看配额告警")
        
        # 获取告警列表
        result = await QuotaService.get_quota_alerts(db)
        
        return ResponseUtil.success(data=result, message="获取配额告警成功")
        
    except Exception as e:
        logger.error(f"获取配额告警失败: {str(e)}")
        return ResponseUtil.error(message=f"获取配额告警失败: {str(e)}")

# 将router对象赋值给speechClientController变量，以便在__init__.py中导入
speechClientController = router 